'use strict';

const request = require('request');
const urlencode = require('urlencode');

const { Controller } = require('egg');

// 引入微信支付插件
const WXPay = require('../../extend/wxpay');
const fs = require('fs');
const wxpay = WXPay({
    appid: 'wx6516e82669c2fe16',
    mch_id: '1641829205',
    partner_key: '342706709xdxl342706709xdxl342706',
    pfx: fs.readFileSync('././apiclient_cert.p12'),
});

class ConfigController extends Controller {
    /**
     * 手机H5支付 */
    async h5pay() {
        const { ctx } = this;
        await ctx.render('http://127.0.0.1:8080/pages/my/index', {});
    }

    /**
     * h5 支付 */
    async h5paySubmit() {
        const { ctx } = this;
        const result = await wxpay.createOutH5Pay({
            body: 'H5支付测试', // 商品描述
            out_trade_no: ctx.request.body.orderNum, //订单编号
            total_fee: 1, //支付总金额（单位：分）
            spbill_create_ip: '192.168.2.56', //付款ip
            notify_url: 'http://localhost:8080/receive/wxReceive', //支付回调地址
            trade_type: 'NATIVE', //支付方式 扫码付
        });
        if (result.return_code == "SUCCESS") {
            // 渲染静态页面，模拟提交表单
            // 此处需要添加支付完成或取消返回的路径
            result.mweb_url = result.mweb_url + "&redirect_url=" + urlencode("http://localhost:8080/#/pages/my/index")
        }
        // console.log(12399);
        console.log(result);

        ctx.status = 200;
        // 处理表单提交后的事件，此处返回表单提交的内容
        ctx.body = `${JSON.stringify(result)}`;
        // ctx.apiSuccess(`${JSON.stringify(result)}`);
    }

    /**
     * 支付回调 */
    async wxReceive() {
        const { ctx } = this;
        console.log("收到支付回调 out");

        // 支付结果异步通知
        wxpay.eggWXCallback(ctx.req, ctx.res, function(msg, req, res) {
            console.log("收到支付回调");
            console.log(msg);
            res.success();
        });
    }

    async topicList() {
        const { ctx, app } = this;
        // const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        // const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const id = ctx.query.id;
        if (!id) {
            ctx.throw('测评id为空')
        };
        let appraisal = await app.model.Appraisal.findOne({
            where: {
                id
            },
            include: [{
                model: app.model.Topic,
                where: {
                    appraisal_id: id
                },
            }]
        });
        if (!appraisal) {
            return ctx.apiSuccess({
                totalCount: 0,
                // currPage: pageNumber,
                list: []
            });
        };
        let list = appraisal.topics;
        // 返回用户信息和token
        ctx.apiSuccess({
            totalCount: appraisal.topics.length,
            // currPage: pageNumber,
            list
        });
    }


    async consultationList() {
        const { ctx, app } = this;
        let consultation = await Promise.all([
            app.model.Consultation.findAll()
        ])

        ctx.apiSuccess(consultation);
    };

    async consultationTypeList() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const type = ctx.query.type ? parseInt(ctx.query.type) : 1;

        let where = {
            coursetype: type
        };
        let { count, rows } = await app.model.Consultation.findAndCountAll({
            where: where,
            offset: (pageNumber - 1) * pageSize,
            limit: pageSize,
        });

        ctx.apiSuccess({
            totalCount: count,
            currPage: pageNumber,
            list: rows
        });
    }

    async consultationDetail() {
        const { ctx, app } = this;
        const { id } = ctx.params;
        const userId = ctx.authUser ? ctx.authUser.id : 0;
        // console.log(id)
        let courses = await app.model.Consultation.findOne({
            where: {
                id: id
            }
        });
        courses = JSON.parse(JSON.stringify(courses))
        courses.collect = 0;
        if (userId) {
            let usercollectList = await app.model.Consultation.findOne({
                where: {
                    userid: userId,
                    courseid: id
                }
            });
            if (usercollectList) {
                courses.collect = 1;
            }
        }
        ctx.apiSuccess(courses);
    }
    async counselorList() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        let consultation = await Promise.all([
            app.model.Counselor.findAll({
                offset: (pageNumber - 1) * pageSize,
                limit: pageSize,
            })
        ])

        ctx.apiSuccess(consultation);
    };

    async counselorListTypeList() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const type = ctx.query.type;
        const { Op } = require("sequelize");
        let where = {
            counselortype: {
                [Op.like]: `%${type}%`
            }
        };
        let { count, rows } = await app.model.Counselor.findAndCountAll({
            where: where,
            offset: (pageNumber - 1) * pageSize,
            limit: pageSize,
        });

        ctx.apiSuccess({
            totalCount: count,
            currPage: pageNumber,
            list: rows
        });
    };
    async counselorDetail() {
        const { ctx, app } = this;
        const { id } = ctx.params;
        // console.log(id)
        let courses = await app.model.Counselor.findOne({
            where: {
                id: id
            }
        });
        courses = JSON.parse(JSON.stringify(courses))

        ctx.apiSuccess(courses);
    }

    // async counselorListTypeList() {
    //         const { ctx, app } = this;
    //         const { id } = ctx.params;
    //         // console.log(id)
    //         let courses = await app.model.Counselor.findOne({
    //             where: {
    //                 id: id
    //             }
    //         });
    //         courses = JSON.parse(JSON.stringify(courses))
    //         ctx.apiSuccess(courses);
    //     }
    // async consulTypeList() {
    //     const { ctx, app } = this;
    //     const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
    //     const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
    //     const type = ctx.query.type ? parseInt(ctx.query.type) : 1;
    //     const types = ctx.query.types ? parseInt(ctx.query.types) : 1;
    //     console.log(type, types);
    //     let where = {
    //         teacherarea: type,
    //         coursetype: types
    //     };
    //     let { count, rows } = await app.model.Consultation.findAndCountAll({
    //         where: where,
    //         offset: (pageNumber - 1) * pageSize,
    //         limit: pageSize,
    //     });

    //     ctx.apiSuccess({
    //         totalCount: count,
    //         currPage: pageNumber,
    //         list: rows
    //     });
    // }

    async configList() {
        const { ctx, app } = this;
        let [swiperList, hotList, livespList] = await Promise.all([
            app.model.Swiper.findAll(),
            app.model.Courses.findAll({
                where: {
                    coursessellstatus: 1
                }
            }),
            app.model.Livesp.findAll()
        ])

        ctx.apiSuccess({ swiperList, hotList, livespList });
    };
    async appraisalConfig() {
        const { ctx, app } = this;

        let [hqxlList, fxwtList, hotList] = await Promise.all([
            app.model.Appraisal.findAll({
                where: {
                    appraisaltype: 1
                }
            }),
            app.model.Appraisal.findAll({
                where: {
                    appraisaltype: 2
                }
            }),

            app.model.Appraisal.findAll({
                where: {
                    appraisalrecommend: 1
                }
            }),
        ])

        // console.log(hqxlList, fxwtList, hotList);
        ctx.apiSuccess({ hqxlList, fxwtList, hotList });
    }

    async appraisalTypeList() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const type = ctx.query.type ? parseInt(ctx.query.type) : 1;

        let where = {
            appraisaltype: type
        };
        let { count, rows } = await app.model.Appraisal.findAndCountAll({
            where: where,
            offset: (pageNumber - 1) * pageSize,
            limit: pageSize,
        });

        ctx.apiSuccess({
            totalCount: count,
            currPage: pageNumber,
            list: rows
        });
    }
    async appraisalDetail() {
        const { ctx, app } = this;
        const { id } = ctx.params;
        let appraisal = await app.model.Appraisal.findOne({
            where: {
                id: id
            }
        });
        ctx.apiSuccess(appraisal);
    }



    async courseConfig() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        let { count, rows } = await app.model.Courses.findAndCountAll({
            offset: (pageNumber - 1) * pageSize,
            limit: pageSize,
            order: [
                ['created_at', 'DESC']
            ]
        });
        // 返回用户信息和token
        ctx.apiSuccess({
            totalCount: count,
            currPage: pageNumber,
            list: rows
        });
    }

    async courseTypeList() {
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const type = ctx.query.type ? parseInt(ctx.query.type) : 1;
        let where = {
            coursestype: type
        };
        let { count, rows } = await app.model.Courses.findAndCountAll({
            where: where,
            offset: (pageNumber - 1) * pageSize,
            limit: pageSize,
        });
        // 返回用户信息和token
        ctx.apiSuccess({
            totalCount: count,
            currPage: pageNumber,
            list: rows
        });
    }
    async search() {
        const { Op } = require("sequelize");
        const { ctx, app } = this;
        const pageSize = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10;
        const pageNumber = ctx.query.pageNumber ? parseInt(ctx.query.pageNumber) : 1;
        const type = ctx.query.type ? parseInt(ctx.query.type) : 1;
        const name = ctx.query.name ? ctx.query.name : '';
        let list = [];
        switch (type) {
            case 1:
                list = await app.model.Counselor.findAll({
                    where: {
                        counselorname: {
                            [Op.like]: `%${name}%`
                        }
                    },
                    offset: (pageNumber - 1) * pageSize,
                    limit: pageSize,
                });
                break;
            case 2:
                list = await app.model.Appraisal.findAll({
                    where: {
                        appraisalname: {
                            [Op.like]: `%${name}%`
                        }
                    },
                    offset: (pageNumber - 1) * pageSize,
                    limit: pageSize,
                });
                break;
            case 3:
                list = await app.model.Courses.findAll({
                    where: {
                        coursesname: {
                            [Op.like]: `%${name}%`
                        }
                    },
                    offset: (pageNumber - 1) * pageSize,
                    limit: pageSize,
                });
                break;
            default:
                list = [];
        };
        // console.log(id)

        ctx.apiSuccess(list);
    }
    async courseDetail() {
        const { ctx, app } = this;
        const { id } = ctx.params;
        const userId = ctx.authUser ? ctx.authUser.id : 0;
        // console.log(id)
        let courses = await app.model.Courses.findOne({
            where: {
                id: id
            }
        });
        courses = JSON.parse(JSON.stringify(courses))
        courses.collect = 0;
        if (userId) {
            let usercollectList = await app.model.Usercollect.findOne({
                where: {
                    userid: userId,
                    courseid: id
                }
            });
            if (usercollectList) {
                courses.collect = 1;
            }
        }
        ctx.apiSuccess(courses);
    }
}

module.exports = ConfigController;